package com.example.TestCode.JavaBasics;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        // 获取类对象
        Class<?> clazz = MyClass.class;

        // 获取构造函数并创建对象
        Constructor<?> constructor = clazz.getConstructor();
        Object obj = constructor.newInstance();

        // 获取方法并调用
        Method method = clazz.getMethod("sayHello", String.class);
        method.invoke(obj, "Alice");

        // 获取字段并访问
        Field field = clazz.getField("publicField");
        System.out.println("Public Field Value: " + field.get(obj));

        Field privateField = clazz.getDeclaredField("privateField");
        privateField.setAccessible(true);
        System.out.println("Private Field Value: " + privateField.get(obj));

        // 获取注解
        Annotation annotation = clazz.getAnnotation(MyAnnotation.class);
        System.out.println("Annotation Value: " + ((MyAnnotation) annotation).value());

        // 动态代理
        InvocationHandler handler = new MyInvocationHandler();
        Class<?>[] interfaces = { MyInterface.class };
        Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, handler);
        ((MyInterface) proxy).doSomething();
    }
}

class MyClass {
    public String publicField = "Public Field";
    private String privateField = "Private Field";

    @MyAnnotation("Hello Annotation")
    public void sayHello(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

interface MyInterface {
    void doSomething();
}

class MyInvocationHandler implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Dynamic Proxy: Before method invocation");
        Object result = method.invoke(proxy, args);
        System.out.println("Dynamic Proxy: After method invocation");
        return result;
    }
}

@interface MyAnnotation {
    String value();
}
